import sqlite3
import os
from flask import g

def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'database.db'))
        db.row_factory = sqlite3.Row
    return db

# 移除@app.teardown_appcontext装饰器，仅保留函数定义
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

def init_db(app):
    with app.app_context():
        db = get_db()
        with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'schema.sql'), 'r', encoding='utf-8') as f:
            db.cursor().executescript(f.read())
        db.commit()